export type getTreeOptionType<T = any> = {
  parentId?: string
  id?: string
  maxdeep?: number
  deepCopy?: boolean
  /**
   * @desc 是否需要自动生成父级链接
   */
  needParentLink?: boolean
  /**
   * @desc 不需要传,内部递归时使用
   */
  parentNode?: TreeObj<T>
  /**
   * @desc 是否需要自动生成level
   */
  needLevel?: boolean
  /**
   * @desc 初始化的level等级
   */
  levelInit?: number
}

const defaultOptions: getTreeOptionType = {
  parentId: 'parentId',
  id: 'id',
  maxdeep: 20,
  deepCopy: true
}
export function getRooteTree<T extends { [key: string]: any }>(
  pid: string,
  arr: T[],
  option: getTreeOptionType<T> = {}
) {
  const {
    parentId = 'parentId',
    id = 'id',
    maxdeep = 20,
    deepCopy = true,
    needParentLink,
    parentNode,
    levelInit = 1,
    needLevel = false
  } = { ...defaultOptions, ...option }

  if (maxdeep > 0) {
    return arr
      .filter((v) => v[parentId] === pid)
      .map((v) => {
        let x: TreeObj<T>
        if (deepCopy) {
          x = { ...v }
        } else {
          x = v
        }
        if (needLevel) {
          x.level = levelInit
        }
        const children = getRooteTree<T>(v[id], arr, {
          ...option,
          parentNode: x,
          levelInit: levelInit + 1,
          maxdeep: maxdeep - 1
        })
        if (children.length) {
          x.children = children
        }
        if (needParentLink) {
          x.parentNode = parentNode
        }
        return x
      })
  } else {
    throw new Error('递归层级过深,请优化数据结构')
  }
}
